﻿<%@ WebHandler Language="C#" Class="resizeImage" %>

using System;
using System.Web;

public class resizeImage : Mgh.Data.Sql.IHttpHandlerBase
{
    int width;
    int height;
    override public void ProcessRequest(HttpContext context)
    {//context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        base.ProcessRequest(context);
        
        String imagename = context.Request.QueryString["iname"] == null ? string.Empty : context.Request.QueryString["iname"];
        String imageid = context.Request.QueryString["id"] == null ? string.Empty : context.Request.QueryString["id"];
        String iw = context.Request.QueryString["iw"] == null ? "100" : context.Request.QueryString["iw"];
        String ih = context.Request.QueryString["ih"] == null ? "100" : context.Request.QueryString["ih"];
        String fw = context.Request.QueryString["fw"] == null ? String.Empty : context.Request.QueryString["fw"];
        String ratio = context.Request.QueryString["ratio"] == null ? "false" : context.Request.QueryString["ratio"];
        Jewelry.BussinessLayer.Properties.Settings set = new Jewelry.BussinessLayer.Properties.Settings();
        if (string.IsNullOrEmpty(imagename))
        {
            Jewelry.BussinessLayer.ProductBLL bn = new Jewelry.BussinessLayer.ProductBLL(getCurrentConnect());
            Jewelry.Entities.DataSources.Jw_Tbl_ProductsDataTable tb = bn.getProduct(imageid);
            if (tb == null || tb.Count == 0)
                imagename = string.Empty;
            imagename = tb[0].IsHinhNull()?string.Empty: tb[0].Hinh;
        }
        string url = VirtualPathUtility.ToAbsolute(set.ImgDirectory + "/" + imagename);
        string mappath = HttpContext.Current.Server.MapPath(url);
        string extention = System.IO.Path.GetExtension(url).ToLower().Remove(0,1);

        if (!extention.Equals("jpg") && !extention.Equals("jpeg") && !extention.Equals("png") && !extention.Equals("gif"))
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("File extension not valid");
            return;
        }
        
        if (string.IsNullOrEmpty(url) || !System.IO.File.Exists(mappath))
        {
            url = VirtualPathUtility.ToAbsolute(set.ImgDirectory + "/" + "default.jpg");
            mappath = HttpContext.Current.Server.MapPath(url);
            extention = System.IO.Path.GetExtension(url).ToLower().Remove(0,1);
        }
        
        context.Response.ContentType = "image/" + extention;
        context.Response.Clear();
        context.Response.BufferOutput = true;

        System.Drawing.Image imageResized;
        if (ratio.ToLower().Equals("true"))
            imageResized = ResizeImageAndUpload(mappath, extention, Convert.ToInt32(ih), Convert.ToInt32(iw), fw);
        else
            imageResized = ResizeImageWithoutRatio(mappath, extention, Convert.ToInt32(ih), Convert.ToInt32(iw));


        if (imageResized != null)
        {
            if (extention.Equals("jpg") || extention.Equals("jpeg"))
            {
                imageResized.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else if (extention.Equals("png"))
            {
                System.IO.MemoryStream memStream = new System.IO.MemoryStream();
                imageResized.Save(memStream, System.Drawing.Imaging.ImageFormat.Png);
                memStream.WriteTo(context.Response.OutputStream);
                memStream.Close();
                //Mestr.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
            }
            else if (extention.Equals("gif"))
            {
                imageResized.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
            }
        }
        else { context.Response.Write("Resize is fail"); context.Response.Close(); }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    public System.Drawing.Image ResizeImageAndUpload(string filePath, string ext, double maxHeight, double maxWidth, string fixWidth)
    {
        try
        {

            // Declare variable for the conversion
            float ratio;
            float newratio;
            // Create variable to hold the image
            System.Drawing.Image thisImage = System.Drawing.Image.FromFile(filePath);

            // Get height and width of current image
            int curwidth = (int)thisImage.Width;
            int curheight = (int)thisImage.Height;
            ratio = (float)curwidth / (float)curheight;
            newratio = (float)maxWidth / (float)maxHeight;
            // Ratio and conversion for new size
            if (ratio == newratio)
            {
                width = (int)maxWidth;
                height = (int)maxHeight;
            }
            if (newratio > ratio)
            {
                width = (int)maxWidth;
                height = (int)((float)(maxWidth * curheight) / (float)curwidth);
            }
            if (newratio < ratio)
            {
                width = (int)((float)(curwidth * maxHeight) / (float)curheight);
                height = (int)maxHeight;
                try
                {
                    if (bool.Parse(fixWidth) == true)
                    {
                        if (width > maxWidth)
                        {
                            height = (int)((float)(maxWidth * height) / (float)width);
                            width = (int)maxWidth;
                        }
                    }
                }
                catch (Exception ex)
                {
                }

            }

            // Create "blank" image for drawing new image
            System.Drawing.Bitmap outImage = new System.Drawing.Bitmap(width, height);
            System.Drawing.Graphics outGraphics = System.Drawing.Graphics.FromImage((System.Drawing.Image)outImage);
            outGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            // Fill "blank" with new sized image
            outGraphics.DrawImage(thisImage, 0, 0, outImage.Width, outImage.Height);
            outGraphics.Dispose();
            thisImage.Dispose();
            if (ext.ToLower().Equals("jpg") || ext.ToLower().Equals("jpeg") || ext.ToLower().Equals("png") || ext.ToLower().Equals("gif"))
                return (System.Drawing.Image)outImage;
            else
                return null;
        }
        catch (Exception ex)
        {
            //Log.Error(ex.Message);
            return null;

        }
    }

    public System.Drawing.Image ResizeImageWithoutRatio(string filePath, string ext, int maxHeight, int maxWidth)
    {
        try
        {
            // Create variable to hold the image
            System.Drawing.Image thisImage = System.Drawing.Image.FromFile(filePath);

            // Create "blank" image for drawing new image
            System.Drawing.Image outImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
            System.Drawing.Graphics outGraphics = System.Drawing.Graphics.FromImage(outImage);
            outGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            outGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            outGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            // Fill "blank" with new sized image
            outGraphics.DrawImage(thisImage, 0, 0, outImage.Width, outImage.Height);
            outGraphics.Dispose();
            thisImage.Dispose();
            if (ext.ToLower().Equals("jpg") || ext.ToLower().Equals("jpeg") || ext.ToLower().Equals("png") || ext.ToLower().Equals("gif"))
                return outImage;
            else
                return null;
        }
        catch (Exception ex)
        {
            //Log.Error(ex.Message);
            return null;

        }
    }

}